﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Diagnostics.CodeAnalysis;
using System.Web.Routing;
using System.Security.Principal;
using MiniBug.Models;
using MiniBug.Authentication;

namespace MiniBug.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {


        public string UserName
        {
            get
            {
                return TempData["UserName"].ToString();
            }
            set
            {
                TempData["UserName"] = value;
            }
        }


            // This constructor is used by the MVC framework to instantiate the controller using
            // the default forms authentication and membership providers.
            public AccountController()
                : this(null, null)
            {
            }

            // This constructor is not used by the MVC framework but is instead provided for ease
            // of unit testing this type. See the comments in AccountModels.cs for more information.
            public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService)
            {
                FormsService = formsService ?? new FormsAuthenticationService();
                MembershipService = membershipService ?? new AccountMembershipService();
            }

            public IFormsAuthenticationService FormsService
            {
                get;
                private set;
            }

            public IMembershipService MembershipService
            {
                get;
                private set;
            }

            protected override void Initialize(RequestContext requestContext)
            {
                if (requestContext.HttpContext.User.Identity is WindowsIdentity)
                {
                    throw new InvalidOperationException("Windows authentication is not supported.");
                }
                else
                {
                    base.Initialize(requestContext);
                }
            }

            protected override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

                base.OnActionExecuting(filterContext);
            }

            [Authorize]
            public ActionResult ChangePassword()
            {
                return View();
            }


            public ActionResult SendToMyPassword(LogOnModel model)
            {
                if (ModelState.IsValid)
                {

                }
               
                return View();
            }


            [Authorize]
            [HttpPost]
            public ActionResult ChangePassword(ChangePasswordModel model)
            {
                if (ModelState.IsValid)
                {
                    if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                    {
                        return RedirectToAction("ChangePasswordSuccess");
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }

                // If we got this far, something failed, redisplay form
                return View(model);
            }


            public ActionResult ChangePasswordSuccess()
            {
                return View();
            }

            public ActionResult ForgottenPassword()
            {
                ViewData["ReturnMessage"] = "";
                return View();
            }

            [HttpPost]
            public ActionResult ForgottenPassword(string email)
            {
                email = email.ToLower();
                using (Entity.MSSQLEntity dbContext = new Entity.MSSQLEntity())
                {
                    var user = (from p in dbContext.User
                                where p.Email.ToLower() == email
                                select p).FirstOrDefault();
                    if (user != null)
                    {
                        MiniBug.Mail.MailSenderConfiguration mailConfig = new Mail.MailSenderConfiguration();
                        MiniBug.Mail.MailSender mail = new Mail.MailSender(mailConfig);
                        string password = MiniBug.Authentication.CryptographProvider.Decrypt(user.Password,user.Login);
                        System.Text.StringBuilder message = new System.Text.StringBuilder();
                        message.Append("Hello ");
                        message.Append(user.Name);
                        message.AppendLine();
                        message.Append("This is an automatic email, please do not reply");
                        message.AppendLine();
                        message.Append("Your username: ");
                        message.Append(user.Login);
                        message.AppendLine("Your password: ");
                        message.Append(password);
                        message.AppendLine();
                        message.AppendLine("Thank you for using MiniBug");
                        mail.Send(user.Email, message.ToString(), "Your Request");
                        ViewData["ReturnMessage"] = "The password was sent to the email address";
                    }
                    else
                    {
                        ViewData["ReturnMessage"] = "The provided email address was not found!";
                    }

                    return View();
                }
            }




            [Authorize]
            public ActionResult LogOff()
            {
                FormsService.SignOut();

                return RedirectToAction("Index", "Home");
            }


            public ActionResult LogOn()
            {
                return View();
            }

            [HttpPost]
            [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
                Justification = "Needs to take same parameter type as Controller.Redirect()")]
            public ActionResult LogOn(LogOnModel model, string returnUrl)
            {
                if (ModelState.IsValid)
                {
                    if (MembershipService.ValidateUser(model.Login, model.Password))
                    {
                        FormsService.SignIn(model.Login, model.RememberMe);                     
                       

                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                }

                // If we got this far, something failed, redisplay form
                return View(model);
            }

            public ActionResult Register()
            {
                return View();
            }


            [HttpPost]
            public ActionResult CheckAvailability(string Username)
            {
                int taken = 0;
                using (Entity.MSSQLEntity dbContext = new Entity.MSSQLEntity())
                {
                    
                    var user = (from p in dbContext.User
                                where p.Login == Username
                                select p).FirstOrDefault();
                    if (user != null)
                    {
                        taken = 1;
                    }
                }               
               
                return Json(taken);
            }

            [HttpPost]
            [CaptchaValidator]
            public ActionResult Register(RegisterModel model, bool captchaValid)
            {
                if (captchaValid)
                {
                    if (ModelState.IsValid)
                    {
                        using (Entity.MSSQLEntity dbContext = new Entity.MSSQLEntity())
                        {

                            var user = (from p in dbContext.User
                                        where p.Email == model.Email
                                        select p).FirstOrDefault();
                            if (user == null)
                            {
                                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Name, model.Login, model.Password, model.Email, model.IsAdmin, model.IsVirtual);

                                if (createStatus == MembershipCreateStatus.Success)
                                {
                                    FormsService.SignIn(model.Login, false);
                                    return RedirectToAction("Index", "Home");
                                }
                                else
                                {
                                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                                }
                            }
                            else 
                            {
                                ModelState.AddModelError("", "Email address already in use");
                            }
                        }              
                        // Attempt to register the user
                       
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The image text is not valid!");
                }
                
                // If we got this far, something failed, redisplay form
                return View(model);
            }

            public virtual void SetAuthenticationCookie(string username)
            {
                FormsAuthentication.SetAuthCookie(username, false);
            }

            private static string ErrorCodeToString(MembershipCreateStatus createStatus)
            {
                // See http://go.microsoft.com/fwlink/?LinkID=177550 for
                // a full list of status codes.
                switch (createStatus)
                {
                    case MembershipCreateStatus.DuplicateUserName:
                        return "Username already exists. Please enter a different user name.";

                    case MembershipCreateStatus.DuplicateEmail:
                        return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                    case MembershipCreateStatus.InvalidPassword:
                        return "The password provided is invalid. Please enter a valid password value.";

                    case MembershipCreateStatus.InvalidEmail:
                        return "The e-mail address provided is invalid. Please check the value and try again.";

                    case MembershipCreateStatus.InvalidAnswer:
                        return "The password retrieval answer provided is invalid. Please check the value and try again.";

                    case MembershipCreateStatus.InvalidQuestion:
                        return "The password retrieval question provided is invalid. Please check the value and try again.";

                    case MembershipCreateStatus.InvalidUserName:
                        return "The user name provided is invalid. Please check the value and try again.";

                    case MembershipCreateStatus.ProviderError:
                        return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                    case MembershipCreateStatus.UserRejected:
                        return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                    default:
                        return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                }
            }

    }
}
